package com.diqye.engine;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.diqye.db.model.XModel;
import com.diqye.engine.Constant.InterceptorKit;
import com.diqye.log.Logger;
import com.google.gson.Gson;

public abstract class Route extends HttpServlet {
	
	private Logger log = Logger.getLogger(getClass());
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public final void init() throws ServletException {
		log.info("初始化 action");
		initAction(Constant.routeActions);
		log.info("初始化 interceptor");
		initInterceptor(Constant.interceptors);
	}
	
	public abstract void initConstant(Constant a);
	public abstract void initAction(RouteActions a);
	public abstract void initInterceptor(InterceptorKit a);

	@Override
	protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String reqmethod = req.getParameter("action");
		//如果是Url请求
		if(reqmethod != null){
			Constant.routeActions.invokConroller(req, resp, reqmethod, null);
			return;
		}
		//如果是JSON请求
		String jsonStr = IOUtils.toString(req.getInputStream(),Constant.encoding);
		@SuppressWarnings("unchecked")
		HashMap<String,Object> modelmap = new Gson().fromJson(jsonStr, HashMap.class);
		XModel model = new XModel();
		model.putAll(modelmap);
		Constant.routeActions.invokConroller(req, resp, model==null?null:model.getToStr("action"), model);
		
	}
	

}
